package com.seamtop.cuber.client;

import com.seamtop.cuber.common.base.DataObject;
import com.seamtop.cuber.common.conf.CuberConfiger;
import com.seamtop.cuber.common.entriy.CuberContants;
import com.seamtop.cuber.common.entriy.CuberMessage;
import com.seamtop.cuber.common.entriy.TableOperatorBean;
import com.seamtop.cuber.common.metadata.TableMetaData;
import com.seamtop.cuber.common.util.CuberUtil;
import com.seamtop.cuber.client.queue.KafkaQueueSender;
import com.seamtop.cuber.client.queue.QueueSenderAdapter;
import com.seamtop.cuber.common.params.ParamsCalibration;
import com.seamtop.cuber.common.util.EncryptUtil;
import com.seamtop.cuber.common.util.StringUtil;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

/**
 * Created by feng on 2015/8/8.
 */
public class RealityOperator implements IOperator {

    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(RealityOperator.class);

    public void execute(CuberMessage message) throws Exception{
        HashMap<String,TableOperatorBean> operatorBeanHashMap = DataObject.getOperatorDataMap();
        HashMap<String,TableMetaData> tableMetaDataMap = DataObject.getMetaDataMap();
        //参数验证
        ParamsCalibration.calibration(message,operatorBeanHashMap,tableMetaDataMap);
        //参数编码
        HashMap<String,Object> msgDataMap = message.getMsgData();
        for(String params:msgDataMap.keySet()){
            String value = msgDataMap.get(params)+"";
            value = URLEncoder.encode(value,"UTF-8");
            msgDataMap.put(params,value);
        }
        //判断是及时发送还是定时发送
        String mode = CuberConfiger.clientConfigProperties.getProperty("send.message.mode");
        if("intime".equals(mode)){//及时发送消息
            String json = CuberUtil.transTaskJson(message);
            LOG.info("CuberClient - send msg:"+json);
            //参数加密
            String encryFlag = CuberConfiger.clientConfigProperties.getProperty("encrypt.flag");
            if(!StringUtil.isEmpty(encryFlag) && "true".equals(encryFlag)){
                json = EncryptUtil.encrypt(json, CuberContants.SERVER_ENCRYPT_KEY);
            }
            QueueSenderAdapter sender = KafkaQueueSender.getInstance();
            sender.send(json);
        }
    }
}
